<template>
    <user-dialog class="menuForm" :title="props.title" :show="props.show" @close="close" @submit="submit">
        <el-form ref="powerForm" label-width="100">
            <el-form-item label="角色名称" prop="roleName">{{props.data?.roleName}}</el-form-item>
            <el-form-item label="角色名称">
                <el-tree ref="permissionTree" :data="list" show-checkbox default-expand-all node-key="menuId"
                    :props="{label:'menuName'}">
                </el-tree>
            </el-form-item>
        </el-form>
    </user-dialog>
</template>

<script setup lang='ts'>
import { ref, watch, PropType, computed, nextTick } from 'vue'
import userDialog from "@/components/Dialog.vue"
import { RoleRow } from "@/interface/role"
import { useStore } from 'vuex'
import { ElTree } from 'element-plus'

const props = defineProps({
    show: {
        type: Boolean,
        default: true,
        required: true
    },
    title: {
        type: String,
        default: '权限设置'
    },
    data: {} as PropType<RoleRow>,
    type: String,
    parentId: Array
})

const store = useStore()
// 权限列表
const list = computed(() => store.state.menuList)
const permissionTree = ref<InstanceType<typeof ElTree>>()
watch(() => props.data?.permissionList, (v) => {
    const arr = v?.checkedKeys
    if (arr) {
        nextTick(() => {
            for (let v of arr) {
                permissionTree.value?.setChecked(v, true, false)
            }
        })
    }
}, { immediate: true })


const emits = defineEmits(["close", "submit"])
const close = () => {
    permissionTree.value?.setCheckedKeys([])
    emits("close")

}
const submit = () => {
    const nodes = permissionTree.value?.getCheckedNodes()
    const halfKeys = permissionTree.value?.getHalfCheckedKeys()
    let checkKeys = [] as string[]
    let parentKeys = [] as string[]
    nodes!.map(node => {
        if (!node.children) {
            checkKeys.push(node.menuId)
        } else {
            parentKeys.push(node.menuId)
        }
    })

    emits("submit", {
        id: props.data!.id,
        checkedKeys: checkKeys,
        halfCheckedKeys: parentKeys.concat(halfKeys as [])
    })
}
</script>
<style lang='scss' scoped>
.el-dialog__header {
    border-bottom: 1px solid red;
}
</style>